<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" class="form">

    <FormItem label="优惠券描述" prop="description">
      <Input v-model="formValidate.description"
             type="textarea"
             :autosize="{minRows: 5,maxRows: 10}"
             :maxlength="descLen"
             @input="descInput">
      </Input>
      <p><span>{{descNum}}</span>/{{descLen}}</p>
    </FormItem>

    <FormItem label="优惠券标题" prop="title">
      <Input v-model="formValidate.title" :maxlength="titleLen" @input="titleInput"></Input>
      <p><span>{{titleNum}}</span>/{{titleLen}}</p>
    </FormItem>

    <FormItem label="投放用户" prop="targetUser">
      <RadioGroup v-model="formValidate.targetUser" vertical>
        <Row>
          <Col span="2">
          <Radio label="2">部分用户</Radio>
          </Col>
          <Col span="10" v-if="formValidate.targetUser=='2'">
            <FormItem label="" prop="consumes" >
              <Upload ref="uploadT"
                      :action="addressFile"
                      :before-upload="handleBeforeUpload"
                      :on-success="handleSuccess"
                      :format="uploadFormatFile"
                      :on-format-error="handleFormatError">
                <Button type="ghost" icon="ios-cloud-upload-outline">上传用户文件</Button>
                <i v-if="isUploadOk">上传成功   &nbsp;&nbsp; &nbsp;  <span style="color: red">{{formValidate.totalCount}}名用户上传成功！{{formValidate.repeatCount}}名重复，已去重。 </span>
                </i>
              </Upload>
            </FormItem>
          </Col>
          <!--<Col v-if="isUploadOk" span="10">
          <span style="color: red">{{formValidate.totalCount}}名用户上传成功！{{formValidate.repeatCount}}名重复，已去重。 </span>
          </Col>-->
        </Row>
        <Row>
          <Col span="2">
          <span @click="fileClear"><Radio label="1" @click="funUser2">全体用户</Radio></span>
          </Col>
        </Row>
      </RadioGroup>

    </FormItem>

    <FormItem label="投放方式" prop="couponAssignType">
      <RadioGroup v-model="formValidate.couponAssignType" vertical>
        <Row>
          <Col span="3">
          <Radio label="1">用户领取</Radio>
          </Col>
          <div v-if="formValidate.couponAssignType=='1'">
            <Col span="2">
            总数量控制：</Col>
            <Col span="6">
            <FormItem prop="upperLimit"><Input v-model="formValidate.upperLimit" type="number"></Input></FormItem>
            </Col>
          </div>
        </Row>
        <Radio label="2">自动发放</Radio>
        <!--
                <Radio label="2">优惠码</Radio>
                <div class="subRadio">
                  <FormItem label=""  prop="couponCodeType">
                    <RadioGroup   v-model="formValidate.couponCodeType" vertical v-show="formValidate.type=='2'">
                      <Radio label="1" class="">一人一码</Radio>

                      <Row>
                        <Col span="24">
                        <Radio label="2" class="">多人一码</Radio>
                        </Col>
                        <div v-show="formValidate.couponCodeType=='2'">
                          <Row>
                            <Col span="2">
                            输入优惠码：</Col>
                            <Col span="8">
                            <Input v-model="formValidate.code" ></Input>
                            </Col>
                          </Row>
                          <Row>
                            <Col span="2">
                            使用次数限制：</Col>
                            <Col span="8">
                            <Input type="number" v-model="formValidate.upperLimit"></Input>
                            </Col>
                          </Row>
                        </div>
                      </Row>
                    </RadioGroup>
                  </FormItem>
                </div>-->
      </RadioGroup>
    </FormItem>

    <FormItem label="优惠券方式" prop="discountType">
      <RadioGroup v-model="formValidate.discountType" vertical>
        <Row>
          <Col span="3">
          <Radio label="1"> 折扣</Radio>
          </Col>
          <div v-if="formValidate.discountType=='1'">
            <Col span="8">
            <FormItem prop="discountPercent">优惠&nbsp;&nbsp;&nbsp;<Input v-model="formValidate.discountPercent"
                                                                        type="number" placeholder="" value="40"
                                                                        style="width: 82%"></Input>&nbsp;%
            </FormItem>
            </Col>
            <!-- <Col span="1"  style="padding-left:0px">
             %</Col>-->
          </div>
        </Row>

        <Row>
          <Col span="3">
          <Radio label="2">现金优惠</Radio>
          </Col>
          <div v-if="formValidate.discountType=='2'">
            <Col span="6">
            <FormItem prop="discountCash">
              <Input v-model="formValidate.discountCash" type="number" placeholder=""></Input>
            </FormItem>
            </Col>
            <Col span="1" class="mode_tip">
            $</Col>
          </div>
        </Row>

        <Row>
          <Col span="3">
          <Radio label="3" disabled>满减</Radio>
          </Col>
          <div v-show="formValidate.discountType=='3'">
            <Col span="1" class="mode_tip">
            满</Col>
            <Col span="3">
            <Input v-model="formValidate.moneyOffPurchase" type="number" placeholder=""></Input></Col>
            <Col span="1" class="mode_tip">
            减</Col>
            <Col span="3">
            <Input v-model="formValidate.moneyOffDiscount" type="number" placeholder=""></Input></Col>
          </div>
        </Row>
      </RadioGroup>
    </FormItem>

    <FormItem label="使用范围" prop="usableRange">
      <RadioGroup v-model="formValidate.usableRange">
        <Radio label="1">全场通用</Radio>
        <Row>
          <Col span="4">
          <Radio label="2">指定套餐</Radio>
          </Col>
          <Col span="6" v-if="formValidate.usableRange=='2'">
          <FormItem prop="combo">
            <Select v-model="formValidate.combo" placeholder="请选择套餐">
              <Option v-for="item in package" :value="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="4">
          <Radio label="3">指定设备</Radio>
          </Col>
          <Col span="6" v-if="formValidate.usableRange=='3'">
          <FormItem  prop="device">
            <Select v-model="formValidate.device" placeholder="请选择设备">
              <Option v-for="item in device" :key="item.value" :value="item.value">{{ item.label }}</Option>

            </Select>
          </FormItem>
          </Col>
        </Row>
      </RadioGroup>
    </FormItem>
    <FormItem label="上下架时间">
      <Row>
        <Col span="4">
        <FormItem prop="beginDate">
          <DatePicker type="date" :options="pickerBeginDateBefore" format="yyyy-MM-dd" placeholder="上架时间"
                      v-model="formValidate.beginDate" ></DatePicker>
        </FormItem>
        </Col>
        <Col span="4">
        <FormItem prop="endDate">
          <DatePicker type="date" :options="pickerBeginDateAfter" format="yyyy-MM-dd" placeholder="下架时间"
                      v-model="formValidate.endDate"></DatePicker>
        </FormItem>
        </Col>
      </Row>
    </FormItem>

    <FormItem label="有效期" prop="expiryDate">
      <Row>
        <Col span="4">
        <Input v-model="formValidate.expiryDate" type="number" placeholder=""></Input>
        </Col>
        <Col span="1" class="mode_tip">
        天</Col>
      </Row>
    </FormItem>

    <FormItem>
      <Button type="primary"  :disabled="sendBtn"  @click="handleSubmit('formValidate')">确定</Button>
      <Button type="ghost" :disabled="sendBtn" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
    </FormItem>
  </Form>
</template>
<script>
  import * as validate from '../../lib/validate'
  import * as fuc from '../../lib/lib'
  import * as Url from '../../api/url'
  import axios from 'axios'
  import { CouponApi, Header } from '../../api/api'
  export default {
    data () {
      const validateUpperLimit = (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('总控制数量不能为0'))
        }else  if (value >= 10000000) {
          callback(new Error('总控制数量数值过大'))
        }else {
          callback()
        }
      };
      const validateExpiryDate = (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('有效期至少为一天'))
        } else {
          callback()
        }
      }
      const validateDiscountPercent = (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('折扣率必须大于0'))
        } else if (value >= 100) {
          callback(new Error('折扣率不能大于等于100'))
        } else if (value == null || value == undefined) {
          callback(new Error('折扣率不能为空'))
        } else if (String(value).indexOf('.') > -1) {
          callback(new Error('折扣率只能为整数'))
        } else {
          callback()
        }
      }
      const validateDiscountCash = (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('优惠金额必须大于0'))
        } else if (value >=19.99) {
          callback(new Error('优惠金额不能大于等于19.99'))
        } else if (value == null || value == undefined) {
          callback(new Error('优惠金额不能为空'))
        } else if (String(value).indexOf('.') > -1) {
          if (value.toString().split('.')[1].length > 2) {
            /* this.formValidate.discountCash =Number(value).toFixed(2);
             console.log(this.formValidate.discountCash)*/
            callback(new Error('优惠金额最多保留2位小数'))
          }else {
            callback()
          }
        } else {
          callback()
        }
      };
      const validateConsumes= (rule, value, callback) => {
        if(this.$refs.uploadT.fileList.length>0){
          callback()
        }else {
          callback(new Error('请选择上传文件'))
        }
      };

      return {
        ID: this.$route.query.id,
        addressFile: Url.root + '/coupons/uploadExcel',//上传地址
        uploadFormatFile: ['xls', 'xlsx'],
        isUploadOk: false,
        editMode: false,
        sendBtn:false,
        uploadList: [],
        package: [],                  //指定套餐

        device: [                     //指定设备
          {value: 1, label: 'snap'},
          {value: 2, label: 'element'},
        ],
        descNum: 0,       //字限制从0开始&#45;&#45;描述
        titleNum: 0,      //字限制从0开始&#45;&#45;标题
        descLen: 255,     //限制&ndash;&gt;优惠券描述
        titleLen: 25,     //限制&ndash;&gt;优惠券标题
        formValidate: {
          combo:"",
          updateBool:false,
          totalCount: '0',//上传总数
          repeatCount: '0',//重复总数
          consumes: '',//接受excel
          description: '',    //优惠券描述
          title: '',       //优惠券标题
          targetUser: '',        //投放用户
          code: '',//优惠券编码
          upperLimit: '',// 优惠券发放上限 -1 表示无上限 ,
          type: '1',        //优惠券类型
          couponAssignType: '',//优惠券发放类型 1.用户领取 2.自动发放 ,
          couponCodeType: '',//优惠码类型 1.一人一码 2.多人一码
          stock: '',//优惠券库存
          discountType: '',//优惠方式 1.折扣 2.现金优惠 3.满减 ,
          discountPercent: '',// 折扣率(仅当 discountType=1 时有效) ,
          discountCash: '',// 现金折扣金额(仅当 discountType=2 时有效) ,
          moneyOffPurchase: '',// 参与满减优惠需要购买的金额数(仅当 discountType=3 时有效) ,
          moneyOffDiscount: '',// 满减优惠，购买指定金额之后的折扣金额(仅当 discountType=3 时有效) ,
          usableRange: '',// 优惠券使用范围 1.全场通用 2.指定套餐 3.指定设备 ,
          usableRangeByCombo: '',// 优惠券可使用的套餐范围(仅当 usableRange=2 时有效) ,
          device:'',// 优惠券可使用的设备范围(仅当 usableRange=3 时有效) ,
          beginDate: '',    //上架时间
          endDate: '',     //下架时间
          expiryDate: '40',//有效期  默认40
        },
        consumesBool:true,
        ruleValidate: {
          combo: [
            { required: true,  type: 'number', message: '请选择套餐', trigger: 'change' }
          ],
          description: [{required: true, message: '描述不能为空'}],
          title: [{required: true, message: '标题不能为空'}],
          targetUser: [{required: true, message: '请选择类型'}],
          consumes: [{required: true, trigger: 'change',message: '请选择上传文件',validator:validateConsumes}],//validator:validateConsumes,
          type: [{required: true, message: '请选择类型'}],
          upperLimit: [{required: true, validator: validateUpperLimit}],
          code: [{required: true, message: '优惠券编码不能为空'}],
          couponAssignType: [{required: true, message: '请选择类型'}],
          couponCodeType: [{required: true, message: '请选择类型'}],//优惠码类型 1.一人一码 2.多人一码
          stock: [{required: this.stock, message: '优惠券库存不能为空'}],//优惠券库存
          discountType: [{required: true, message: '请选择优惠方式'}],
          discountPercent: [{required: true, validator: validateDiscountPercent, trigger: 'blur'}],// 折扣率(仅当 discountType=1 时有效) ,
          discountCash: [{required: true, validator: validateDiscountCash}],// 现金折扣金额(仅当 discountType=2 时有效) ,
          //moneyOffPurchase: [{ required: true, message: '金额不能为空' }],// 参与满减优惠需要购买的金额数(仅当 discountType=3 时有效) ,
          //moneyOffDiscount: [{ required: true, message: '金额不能为空' }],// 满减优惠，购买指定金额之后的折扣金额(仅当 discountType=3 时有效) ,
          usableRangeByCombo:[{required: true, message: '请选择范围',trigger: 'change'}],// 优惠券可使用的套餐范围(仅当 usableRange=2 时有效) ,
          device:[{ required: true,type:'number', message: '请选择设备', trigger: 'change' }],// 优惠券可使用的设备范围(仅当 usableRange=3 时有效) ,
          usableRange: [{required: true, message: '请选择类型'}],
          beginDate: [
            { required: true, type: 'date', message: '请选择上架时间', trigger: 'change' }
          ],
          endDate: [ { required: true, type: 'date', message: '请选择下架时间', trigger: 'change' }],
          expiryDate: [{required: true, validator: validateExpiryDate}]
        },
        pickerBeginDateBefore: {
          disabledDate: (date) => {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
        pickerBeginDateAfter: {
          disabledDate: (date) => {
            let beginDateVal = this.formValidate.beginDate;
            if (beginDateVal) {
              return date.getTime() < beginDateVal;
            }
            //return date && date.valueOf() < Date.now() - 86400000
          }
        },
      }

    },
    watch: {
     /* isUploadOk: function (val, oldVal) {
        console.log('new: %s, old: %s', val, oldVal);
        this.isUploadOk =val;
        this.formValidate.updateBool =val;
      }*/
    },
    updated: function() {

    },
    computed: {
     /* geTimestart(date){
        this.formValidate.beginDate = date
      },*/
     /* geTimend(date){
        this.formValidate.endDate = date
      }*/
    },
    mounted: function () {
      this.$nextTick(function () {
        this.getSnapPaymentCombo()
        if (this.ID == '' || this.ID == 'undefined' || this.ID == null) {
          this.ID = 0
        } else {
          this.editMode = true
          this.pageFromXqing()
        }
      })
    },
    methods: {
      getSnapPaymentCombo(){
        axios.get(Url.couponsGetSnapPaymentCombo).then(response => {
          //console.log(response.data);
          let result = response.data
          if (result.messageCode == '200') {
            if (result.data != undefined) {
              for (let i = 0; i < result.data.length; i++) {
                this.package.push({value: i + 1, label: result.data[i].name})
              }
            }
          }
        }).catch(error => {
        })

      },
      pageFromXqing(){
        //this.uploadList=[];
        axios.post(Url.coupons + this.ID).then(response => {
          let result = response.data.data
          if (result != undefined) {
            this.formValidate.consumes = result.consumes   //接受excel
            this.formValidate.description = result.description   //优惠券描述
            this.formValidate.title = result.title     //优惠券标题
            this.formValidate.targetUser = result.targetUser        //投放用户
            this.formValidate.type = result.type        //优惠券类型
            this.formValidate.couponAssignType = result.couponAssignType//优惠券发放类型 1.用户领取 2.自动发放 ,
            this.formValidate.couponCodeType = result.couponCodeType//优惠码类型 1.一人一码 2.多人一码
            this.formValidate.upperLimit = result.upperLimit//优惠券库存
            this.formValidate.discountType = result.discountType//优惠方式 1.折扣 2.现金优惠 3.满减 ,
            this.formValidate.discountPercent = result.discountPercent// 折扣率(仅当 discountType=1 时有效) ,
            this.formValidate.discountCash = result.discountCash// 现金折扣金额(仅当 discountType=2 时有效) ,
            this.formValidate.moneyOffPurchase = result.moneyOffPurchase// 参与满减优惠需要购买的金额数(仅当 discountType=3 时有效) ,
            this.formValidate.moneyOffDiscount = result.moneyOffDiscount// 满减优惠，购买指定金额之后的折扣金额(仅当 discountType=3 时有效) ,
            this.formValidate.usableRange = result.usableRange// 优惠券使用范围 1.全场通用 2.指定套餐 3.指定设备 ,
            this.formValidate.combo = result.usableRangeByCombo// 优惠券可使用的套餐范围(仅当 usableRange=2 时有效) ,
            this.formValidate.device = result.usableRangeByDevice// 优惠券可使用的设备范围(仅当 usableRange=3 时有效) ,
            this.formValidate.beginDate = result.beginDate    //上架时间
            this.formValidate.endDate = result.endDate     //下架时间
            this.formValidate.expiryDate = result.expiryDate//有效期  默认40
          }

        }).catch(error => {
        })
       // this.uploadList = this.$refs.uploadFile.fileList;
      },
      descInput(){
        this.descNum = this.formValidate.description.length
      },
      titleInput(){
        this.titleNum = this.formValidate.title.length
      },
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.sendBtn =!this.sendBtn;
            var data = {
              id: this.ID,
              description: this.formValidate.description,    //优惠券描述
              title: this.formValidate.title,       //优惠券标题
              targetUser: this.formValidate.targetUser,        //投放用户
              type: this.formValidate.type,        //优惠券类型
              consumes: this.formValidate.consumes,
              code: this.formValidate.code,   //优惠券编码
              upperLimit: this.formValidate.couponAssignType == 1 ? this.formValidate.upperLimit : null,//限制次数
              couponAssignType: this.formValidate.couponAssignType,//优惠券发放类型 1.用户领取 2.自动发放 ,
              couponCodeType: null,//优惠码类型 1.一人一码 2.多人一码
              stock: this.formValidate.stock,//优惠券库存
              discountType: this.formValidate.discountType,//优惠方式 1.折扣 2.现金优惠 3.满减 ,
              discountPercent: this.formValidate.discountType == 1 ? this.formValidate.discountPercent : null,// 折扣率(仅当 discountType=1 时有效) ,
              discountCash: this.formValidate.discountType == 2 ? this.formValidate.discountCash : null,// 现金折扣金额(仅当 discountType=2 时有效) ,
              moneyOffPurchase: null,// 参与满减优惠需要购买的金额数(仅当 discountType=3 时有效) ,
              moneyOffDiscount: null,// 满减优惠，购买指定金额之后的折扣金额(仅当 discountType=3 时有效) ,
              usableRange: this.formValidate.usableRange,// 优惠券使用范围 1.全场通用 2.指定套餐 3.指定设备 ,
              usableRangeByCombo: this.formValidate.usableRange == 2 ? this.formValidate.combo : null,// 优惠券可使用的套餐范围(仅当 usableRange=2 时有效) ,
              usableRangeByDevice: this.formValidate.usableRange == 3 ? this.formValidate.device : null,// 优惠券可使用的设备范围(仅当 usableRange=3 时有效) ,
              beginDate:fuc.dateFormatYMD(this.formValidate.beginDate)!="NaN-NaN-NaN"?fuc.dateFormatYMD(this.formValidate.beginDate):null,    //上架时间
              endDate: fuc.dateFormatYMD(this.formValidate.endDate) !="NaN-NaN-NaN"?fuc.dateFormatYMD(this.formValidate.endDate):null,     //下架时间
              expiryDate: this.formValidate.expiryDate//有效期  默认40，

            }
            if (this.editMode) {
              this.editCoupons(data,name)
            } else {
              this.addCoupons(data,name)
            }
          } else {
            //this.$Message.error('表单验证失败!')
          }
        })

      },
      addCoupons(data,name){
        CouponApi.getCoupons(data, {header: Header}).then(response => {
          if (response.messageCode == 200) {
            this.handleReset('formValidate');
            this.sendBtn =!this.sendBtn;
            this.$router.push({path: '/couponsList'})
            //this.$Message.success('优惠券添加成功！')
          }
        }).catch(error => {
          this.$Message.error('优惠券添加失败！')
          this.sendBtn = false
        })
      },
      editCoupons(data,name){
        axios.patch(Url.coupons + this.ID, data).then(response => {
          if (response.data.messageCode == 200) {
            this.handleReset('formValidate');
            this.sendBtn =!this.sendBtn;
            this.$router.push({path: '/couponsList'})
            //this.$Message.success('优惠券编辑成功！')
          } else {
            this.$Message.error('优惠券编辑失败！')
            this.sendBtn = false
          }
        }).catch(error => {
          this.sendBtn = false
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields();
        this.isUploadOk = false;
      },
      handleFormatError (file) {
        this.$Message.error(file.name + '格式不正确,请上传xls、xlsx格式文件')
      },
      handleSuccess(response, file, fileList){
        this.uploadList =fileList;

            this.isUploadOk = true
            this.formValidate.consumes = response.consumes
            this.formValidate.totalCount = response.totalCount
            this.formValidate.repeatCount = response.repeatCount
            //this.handleSubmit('formValidate');

      },

      handleBeforeUpload (file) {
        const check = this.uploadList.length < 1
        if (!check) {
          this.$Message.error('只能上传一个文件');
        }
        return check
      },
      handleError(error, file, fileList){

      },
      fileClear(){
        this.isUploadOk = false
        this.uploadList = []
      }
    }
  }
</script>
<style scoped>
  .ivu-radio-group {
    display: block;
    font-size: 12px;
    vertical-align: middle;
  }

  .form {
    margin-top: 20px;
    margin-right: 20px;
  }

  .subRadio {
    padding-left: 20px;
    margin-bottom: 20px;
  }

  /*优惠方式*/
  .mode_tip {
    text-align: left;
    padding-left: 20px;
  }
</style>
